package test2.redis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import redis.clients.jedis.Jedis;

public class LuaRedis {
	
	String script = "";
	
	static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	static String key1 = "tv";
	static String key3 = "buytv";
	
	public static void main(String[] args) {
		String script = readfile();
		Jedis jedis = new Jedis();
		jedis.del(key3);
		jedis.close();
		for(int i=0;i<50;i++) {
			threadpool.submit(new Runnable() {
				@Override
				public void run() {
					Jedis jedis = new Jedis();
					Object ret = null;
					try {
						ret = jedis.eval(script, Arrays.asList(new String[]{key1}), Collections.emptyList());
					} catch (Exception e) {
						e.printStackTrace();
					}
					long result = (long)ret;
					if(result==0) {
						System.out.println("卖没了，没抢到");
					} else if(result==1) {
						System.out.println("恭喜你，你是第"+jedis.incr(key3)+"抢到的用户");
					}
					jedis.close();
				}
			});
		}
		threadpool.shutdown();
		
//		Jedis jedis = new Jedis();
//		Object ret = jedis.eval(script, Arrays.asList(new String[]{key1, key2}), Collections.EMPTY_LIST);
//		System.out.println(ret);
//		jedis.close();
		
	}
	
	static String readfile() {
		InputStream is = LuaRedis.class.getResourceAsStream("demo.lua");
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String str = "";
		while(true) {
			String line = null;
			try {
				line = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(line!=null) {
				str += line;
			} else {
				break;
			}
		}
		return str;
	}

}
